<template>
  <div class="app-container">
    <el-form ref="queryFormRef" :model="page.queryForm" inline>
      <el-form-item label="角色名称" prop="role_name">
        <el-input
          v-model="page.queryForm.role_name"
          @keyup.enter="getRoleList"
          clearable
          placeholder="请输入角色名称"
        ></el-input>
      </el-form-item>
      <el-form-item label="权限字符" prop="role_key">
        <el-input
          v-model="page.queryForm.role_key"
          @keyup.enter="getRoleList"
          clearable
          placeholder="请输入权限字符"
        ></el-input>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="page.queryForm.status" style="width: 140px">
          <el-option label="正常" value="0" />
          <el-option label="停用" value="1" />
        </el-select>
      </el-form-item>

      <el-form-item label="创建时间" prop="create_time">
        <el-date-picker
          v-model="daterange"
          type="daterange"
          format="YYYY-MM-DD"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @change="handleDateChange"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="getRoleList"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <vxe-toolbar
      ref="toolbarRef"
      custom
      print
      :refresh="{ query: getRoleList }"
    >
      <template #buttons>
        <el-button type="primary" icon="Plus" plain @click="handleAdd()"
          >新增</el-button
        >
        <el-button type="success" icon="Edit" plain @click="handleUpdate()"
          >修改</el-button
        >
        <el-popconfirm
          title="您确定要删除选中的数据吗?"
          confirm-button-text="确认"
          cancel-button-text="取消"
          @confirm="handleDelete()"
        >
          <template #reference>
            <el-button type="danger" icon="Delete" plain>删除</el-button>
          </template>
        </el-popconfirm>
        <el-button type="warning" icon="Download" plain @click="handleExport()"
          >导出</el-button
        >
      </template>
    </vxe-toolbar>

    <vxe-table
      ref="roleTableRef"
      border="inner"
      align="center"
      :column-config="{ resizable: true }"
      :row-config="{ isHover: true }"
      :print-config="{}"
      :loading="loading"
      :data="tableData"
      @checkbox-all="selectAllChangeEvent"
      @checkbox-change="selectChangeEvent"
    >
      <vxe-column type="checkbox" width="60"></vxe-column>
      <vxe-column field="role_id" title="角色ID" width="100"></vxe-column>
      <vxe-column field="role_name" title="角色名称"></vxe-column>
      <vxe-column field="role_key" title="权限字符"></vxe-column>
      <vxe-column field="role_sort" title="显示顺序" width="100"></vxe-column>
      <vxe-column title="状态">
        <template #default="{ row }">
          <el-switch
            v-model="row.status"
            active-value="0"
            inactive-value="1"
            @change="handleStatusChange(row)"
          ></el-switch>
        </template>
      </vxe-column>
      <vxe-column field="create_time" title="创建时间"></vxe-column>
      <vxe-column title="操作">
        <template #default="{ row }">
          <el-button
            v-if="row.role_id != 1"
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(row)"
            >修改</el-button
          >
          <el-popconfirm
            v-if="row.role_id != 1"
            title="您确定要删除此数据吗?"
            confirm-button-text="确认"
            cancel-button-text="取消"
            @confirm="handleDelete(row)"
          >
            <template #reference>
              <el-button link type="primary" icon="Delete">删除</el-button>
            </template>
          </el-popconfirm>
          <el-button
            v-if="row.role_id != 1"
            link
            type="primary"
            icon="Key"
            @click="handleDataPerm(row)"
            >数据权限</el-button
          >
        </template>
      </vxe-column>
    </vxe-table>

    <el-row justify="end" style="padding: 16px">
      <el-pagination
        v-show="page.total > 0"
        v-model:current-page="page.queryForm.pageNum"
        v-model:page-size="page.queryForm.pageSize"
        :page-sizes="[10, 20, 30, 40]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.total"
        @size-change="getRoleList"
        @current-change="getRoleList"
      />
    </el-row>

    <!-- 新增、修改表单 -->
    <el-dialog
      v-model="open"
      :title="title"
      width="500px"
      append-to-body
      destroy-on-close
      @closed="reset"
    >
      <el-form
        ref="formRef"
        :model="page.form"
        :rules="page.rules"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="role_name">
          <el-input
            v-model="page.form.role_name"
            clearable
            placeholder="请输入角色名称"
          />
        </el-form-item>
        <el-form-item prop="role_key">
          <template #label>
            <span>
              <el-tooltip
                content="控制器中定义的权限字符，如：@PreAuthorize(`@ss.hasRole('admin')`)"
                placement="top"
              >
                <el-icon><question-filled /></el-icon>
              </el-tooltip>
              权限字符
            </span>
          </template>
          <el-input
            v-model="page.form.role_key"
            clearable
            placeholder="请输入权限字符"
          ></el-input>
        </el-form-item>
        <el-form-item label="角色顺序" prop="role_sort">
          <el-input-number v-model="page.form.role_sort" :min="0" :max="99" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="page.form.status">
            <el-radio label="0">正常</el-radio>
            <el-radio label="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="菜单权限" prop="menu_ids">
          <el-checkbox
            v-model="menuExpand"
            label="展开/折叠"
            @change="handleTreeExpandAll($event, menuRef)"
          />
          <el-checkbox
            v-model="menuAllChecked"
            label="全选/全不选"
            @change="handleTreeCheckedAll($event, 'menu')"
          />
          <el-checkbox
            v-model="page.form.menu_check_strictly"
            label="父子联动"
          />
          <el-tree
            class="tree-border"
            ref="menuRef"
            :data="menuOptions"
            :default-checked-keys="page.menuIds"
            show-checkbox
            node-key="menu_id"
            :props="{
              value: 'menu_id',
              label: 'menu_name',
              children: 'children',
            }"
            :check-strictly="!page.form.menu_check_strictly"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="page.form.remark"
            type="textarea"
            placeholder="请输入内容"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="submit">确认</el-button>
      </template>
    </el-dialog>

    <!-- 数据权限表单 -->
    <el-dialog
      v-model="openDataPerm"
      title="分配数据权限"
      width="500px"
      :default-checked-keys="page.deptIds"
      append-to-body
      destroy-on-close
      @closed="resetDataPerm"
    >
      <el-form :model="page.form" :rules="page.rules" label-width="100px">
        <el-form-item label="角色名称">
          <el-input
            v-model="page.form.role_name"
            disabled
            placeholder="请输入角色名称"
          ></el-input>
        </el-form-item>

        <el-form-item label="权限字符">
          <el-input
            v-model="page.form.role_key"
            disabled
            placeholder="请输入权限字符"
          ></el-input>
        </el-form-item>

        <el-form-item label="权限范围">
          <el-select v-model="page.form.role_scope">
            <el-option
              v-for="item in permFields"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item v-show="page.form.role_scope == '2'" label="数据权限">
          <el-checkbox
            v-model="deptExpand"
            label="展开/折叠"
            @change="handleTreeExpandAll($event, deptRef)"
          />
          <el-checkbox
            v-model="deptAllChecked"
            label="全选/全不选"
            @change="handleTreeCheckedAll($event, 'dept')"
          />
          <el-checkbox
            v-model="page.form.dept_check_strictly"
            label="父子联动"
          />
          <el-tree
            class="tree-border"
            ref="deptRef"
            :data="deptOptions"
            :default-checked-keys="page.deptIds"
            show-checkbox
            node-key="dept_id"
            :props="{
              value: 'dept_id',
              label: 'dept_name',
              children: 'children',
            }"
            :check-strictly="!page.form.dept_check_strictly"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="cancelDataPerm">取消</el-button>
        <el-button type="primary" @click="submitDataPerm">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from "vue";
import {
  roleList,
  roleAdd,
  roleEdit,
  roleDel,
  roleInfo,
  roleExport,
} from "@/api/system/role.ts";
import { menuList } from "@/api/system/menu.ts";
import { deptList } from "@/api/system/dept.ts";
import { downloadFile } from "@/utils/download.ts";

const queryFormRef = ref();
const daterange = ref([]);
const roleTableRef = ref();
const toolbarRef = ref();
const formRef = ref();
const menuRef = ref();
const deptRef = ref();

const page = reactive({
  // 查询表单
  queryForm: {
    role_name: null,
    role_key: null,
    status: null,
    begin_time: null,
    end_time: null,
    pageNum: 1,
    pageSize: 10,
  },
  total: 0,
  menuIds: [],
  deptIds: [],
  // 新增、修改表单
  form: {},
  // 新增、修改表单验证规则
  rules: {
    role_name: [
      { required: true, message: "角色名称不能为空", trigger: "blur" },
    ],
    role_key: [
      { required: true, message: "权限字符不能为空", trigger: "blur" },
    ],
    role_sort: [
      { required: true, message: "角色顺序不能为空", trigger: "blur" },
    ],
  },
});

// 表格数据
const tableData = ref([]);
// 选中的表格ID
const checkedIds = ref([]);
// 加载状态
const loading = ref(false);
// 新增、修改对话框的显示与隐藏
const open = ref(false);
// 对话框标题
const title = ref("");
// 菜单树选项
const menuOptions = ref([]);
// 树组件是否展开
const menuExpand = ref(false);
// 全选状态
const menuAllChecked = ref(false);

// 数据权限对话框的显示与隐藏
const openDataPerm = ref(false);
// 部门树选项
const deptOptions = ref([]);
// 数据权限树组件是否展开
const deptExpand = ref(false);
// 数据权限树组件是否全选
const deptAllChecked = ref(false);
// 权限范围下拉
const permFields = ref([
  { value: "1", label: "全部数据权限" },
  { value: "2", label: "自定数据权限" },
  { value: "3", label: "本部门数据权限" },
  { value: "4", label: "本部门及以下数据权限" },
  { value: "5", label: "仅本人数据权限" },
]);

nextTick(() => {
  // 将表格和工具栏进行关联
  const $table = roleTableRef.value;
  const $toolbar = toolbarRef.value;
  if ($table && $toolbar) {
    $table.connect($toolbar);
  }
});

onMounted(() => {
  getRoleList();
  resetForm();
  getMenuTree();
  getDeptTree();
});

/**
 * 创建日期范围改变
 * @param {*} e
 */
function handleDateChange(e) {
  if (e) {
    page.queryForm.begin_time = e[0];
    page.queryForm.end_time = e[1];
  } else {
    page.queryForm.begin_time = null;
    page.queryForm.end_time = null;
  }
}

/**
 * 重置查询
 */
function resetQuery() {
  queryFormRef.value.resetFields();
  daterange.value = [];
  page.queryForm.begin_time = null;
  page.queryForm.end_time = null;
  getRoleList();
}

/**
 * 表格全选事件
 * @param {*} e
 */
function selectAllChangeEvent(e) {
  checkedIds.value = e.records.map((item) => item.role_id);
}

/**
 * 表格选中事件
 * @param {*} e
 */
function selectChangeEvent(e) {
  checkedIds.value = e.records.map((item) => item.role_id);
}

/**
 * 新增角色
 */
function handleAdd(row = null) {
  if (row) {
    page.form.parent_id = row.role_id;
    page.form.role_type = row.role_type;
  }
  open.value = true;
  title.value = "新增角色";
}

/**
 * 修改角色
 * @param {Object} row 行数据
 */
function handleUpdate(row) {
  let ids = row ? [row.role_id] : checkedIds.value;
  if (ids.length == 0) {
    return ElMessage.warning("请选择要修改的角色");
  } else if (ids.length > 1) {
    return ElMessage.warning("只能选择一个角色");
  }
  roleInfo(row.role_id).then((res) => {
    page.menuIds = res.data.roleMenus;
    open.value = true;
    title.value = "修改角色";
    // 文档说的是重置为初始值，当我们打开对话框时，我们已经赋值完毕了，所以使用resetFields会重置到赋完值的状态
    // 这里，我们借助nextTick去修改数据渲染页面：(不要忘记引用nextTick)
    nextTick(() => {
      page.form = {
        ...res.data.role,
        menu_check_strictly: res.data.role.menu_check_strictly ? true : false,
      };
    });
  });
}

/**
 * 分配数据权限
 * @param {*} row
 */
function handleDataPerm(row) {
  roleInfo(row.role_id).then((res) => {
    page.deptIds = res.data.roleDepts;
    openDataPerm.value = true;
    nextTick(() => {
      page.form = {
        ...res.data.role,
        dept_check_strictly: res.data.role.dept_check_strictly ? true : false,
      };
    });
  });
}

/**
 * 删除角色
 * @param {Object} row 行数据
 */
function handleDelete(row) {
  let ids = row ? [row.role_id] : checkedIds.value;
  if (ids.length == 0) {
    return ElMessage.warning("请选择要删除的角色");
  }
  roleDel({ roleIds: ids }).then((res) => {
    getRoleList();
  });
}

/**
 * 获取角色列表
 */
function getRoleList() {
  loading.value = true;
  roleList(page.queryForm)
    .then((res) => {
      tableData.value = res.data.list;
      page.total = res.data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/**
 * 状态改变
 * @param {Object} row 行数据
 */
function handleStatusChange(row) {
  roleEdit(row.role_id, {
    role: {
      status: row.status,
    },
  }).then((res) => {
    ElMessage.success("修改成功");
    getRoleList();
  });
}

/**
 * 提交新增、修改
 */
function submit() {
  page.menuIds = menuRef.value.getCheckedKeys();
  formRef.value.validate((valid) => {
    if (valid) {
      if (page.form.role_id) {
        roleEdit(page.form.role_id, {
          role: page.form,
          menuIds: page.menuIds,
        }).then((res) => {
          open.value = false;
          ElMessage.success("修改成功");
          getRoleList();
        });
      } else {
        roleAdd({ role: page.form, menuIds: page.menuIds }).then((res) => {
          open.value = false;
          ElMessage.success("新增成功");
          getRoleList();
        });
      }
    }
  });
}

/**
 * 提交分配权限
 */
function submitDataPerm() {
  page.deptIds = deptRef.value.getCheckedKeys();
  roleEdit(page.form.role_id, {
    role: page.form,
    deptIds: page.deptIds,
  }).then((res) => {
    openDataPerm.value = false;
    ElMessage.success("分配权限成功");
  });
}

/**
 * 取消
 */
function cancel() {
  open.value = false;
}

/**
 * 重置
 */
function reset() {
  resetForm();
  menuRef.value.setCheckedNodes([]);
  page.menuIds = [];
}

/**
 * 取消分配数据权限
 */
function cancelDataPerm() {
  openDataPerm.value = false;
}

/**
 * 重置数据权限
 */
function resetDataPerm() {
  resetForm();
  deptRef.value.setCheckedKeys([]);
  page.deptIds = [];
}

/**
 * 重置表单
 */
function resetForm() {
  page.form = {
    role_id: null,
    role_name: null,
    role_key: null,
    role_sort: 0,
    role_scope: "1",
    status: "0",
    menu_check_strictly: true,
    dept_check_strictly: true,
    remark: null,
  };
}

/**
 * 获取菜单树
 */
function getMenuTree() {
  menuList().then((res) => {
    menuOptions.value = listToMenuTree(res.data, "0");
  });
}

/**
 * 获取部门树
 */
function getDeptTree() {
  deptList().then((res) => {
    deptOptions.value = listToDeptTree(res.data, "0");
  });
}

/**
 * 列表转菜单树
 * @param {Array} list 列表
 * @param {String} parentId 父级id
 */
function listToMenuTree(list, parentId) {
  return list
    .filter((item) => item.parent_id === parentId)
    .map((item) => ({
      ...item,
      menu_id: Number(item.menu_id),
      children: listToMenuTree(list, item.menu_id),
    }));
}

/**
 * 列表转部门树
 * @param {Array} list 列表
 * @param {String} parentId 父级id
 */
function listToDeptTree(list, parentId) {
  return list
    .filter((item) => item.parent_id === parentId)
    .map((item) => ({
      ...item,
      dept_id: Number(item.dept_id),
      children: listToDeptTree(list, item.dept_id),
    }));
}

/**
 * 树组件的展开与折叠
 * @param {Boolean} value 是否展开
 * @param $ref  树组件实例
 */
function handleTreeExpandAll(value, $ref) {
  if (!$ref) return;
  // 此处调用的tree组件内部的属性
  Object.values($ref.store.nodesMap).forEach((node) => {
    node.expanded = value;
  });
}

/**
 * 树组件的全选/全不选
 * @param {Boolean} value 是否选中
 * @param type  树组件类型
 * 这里使用树组件的展开handleTreeExpandAll方法无法处理半选的情况
 */
function handleTreeCheckedAll(value, type) {
  if (type === "menu") {
    menuRef.value.setCheckedNodes(value ? menuOptions.value : []);
  } else {
    deptRef.value.setCheckedNodes(value ? deptOptions.value : []);
  }
}

/**
 * 导出
 */
function handleExport() {
  roleExport().then((res) => {
    downloadFile(res);
  });
}
</script>

<style lang="scss" scoped>
.tree-border {
  margin-top: 5px;
  border: 1px solid #e5e6e7;
  background: #ffffff none;
  border-radius: 4px;
  width: 100%;
}
</style>
